$().ready(function() {
    // getPurchaseByUpdate(getPurchaseId())
    // getMarshallingByUpdate(getMarshallingId())
    formatDate()
    addMaterialsList()
	validateRule();
});

$.validator.setDefaults({
	submitHandler : function() {
		update();
	}
});
function update() {
    var data = buildData();
    if (!data.materials || data.materials.length == 0) {
        layer.alert("请选择原材料");
        return false
    }
	$.ajax({
		cache : true,
		type : "POST",
        dataType : "JSON",
        contentType: "application/json",
		url : getProjectName()+"/produce/scAdditive/update",
		//data : $('#signupForm').serialize(),// 你的formid
        data : JSON.stringify(data),
		async : false,
		error : function(request) {
			parent.layer.alert("Connection error");
		},
		success : function(data) {
			if (data.code == 0) {
				parent.layer.msg("操作成功");
				parent.reLoad();
				var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
				parent.layer.close(index);

			} else {
				parent.layer.alert(data.msg)
			}

		}
	});

}
function validateRule() {
	var icon = "<i class='fa fa-times-circle'></i> ";
	$("#signupForm").validate({
        rules : {
            number : {
                required : true
            },
            weighingBy : {
                required : true
            },
            checkBy : {
                required : true
            },
            additiveDate : {
                required : true
            }
        },
        messages : {
            number : {
                required : icon + "请输入数量"
            },
            weighingBy : {
                required : icon + "请输入称量人"
            },
            checkBy : {
                required : icon + "请输入复核人"
            },
            additiveDate : {
                required : icon + "请输入配添加剂时间"
            }
        }
	})
}

function buildData() {
    var data = {};
    data.additiveId = $("#signupForm input[name=additiveId]").val();
    data.produceTaskId = $("#signupForm input[name=produceTaskId]").val();
    data.purchaseId = $("#signupForm select[name=purchaseId] option:selected").val();
    //data.number = $("#signupForm input[name=number]").val();
    data.weighingBy = $("#signupForm input[name=weighingBy]").val();
    data.checkBy = $("#signupForm input[name=checkBy]").val();
    data.additiveDate = $("#signupForm input[name=additiveDate]").val();
    data.materials = buildmaterials();

    return data;
}

function buildmaterials() {
    var materials = [];
    $("#signupForm .product-list div[class =product-group]").each(function () {
        var material = {};
        material.materialId = $(this).children("input[name=number]").attr("id");
        material.materialSize = $(this).children("input[name=number]").val();
        material.batch = $(this).children("input[name=batch]").val();

        materials.push(material);
        console.log(materials)
    });
    return materials;
}


var productIndex;
$(document).on("click", "a,i", function () {
    switch ($(this).attr("option")) {
        case "materialSelect": {
            productSelect();
            break;
        }
        case "materialDelete": {
            $(this).parents("div[class=product-group]").remove();
        }
    }
});
/**
 *
 */
function productSelect() {
    productIndex = layer.open({
        type: 2,
        title: '选择原材料',
        maxmin: false,
        shadeClose: false, // 点击遮罩关闭层
        area: ['100%', '100%'],
        content: getProjectName()+'/produce/scAdditive/material/select' // iframe的url
    });
}

/**
 *
 * @param data
 */
window.materialCallback = function (data) {
    var hasExist = false;
    $(".product-list div[class=product-group]").each(function () {
        if ($(this).attr("id") === data.materialId) {
            hasExist = true;
        }
    });

    if (hasExist) {
        layer.msg(data.materialName + "已经选择");
        return;
    }

    var div = $('<div id="' + data.materialId + '" class="product-group"></div>');
    $(div).append('<span>' + data.materialName + '</span>');
    $(div).append('<input id="' + data.materialId + '" class="form-control" name="batch" type="" required placeholder="原材料批次(必填)">');
    $(div).append('<input id="' + data.materialId + '" class="form-control" name="number" type="" required placeholder="原材料数量(必填)">');
    $(div).append('<i class="fa fa-remove" option="materialDelete"></i>');
    $(".product-list").append(div);
    layer.close(productIndex);
};